/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginCodeDialog.java
 *
 * Created on Jul 6, 2011, 11:07:30 PM
 */

package ua.pp.bizon.yandex.nb;

import ua.pp.bizon.yandex.api.IHttpRemoteUtils;
import ua.pp.bizon.yandex.api.ILogin;
import ua.pp.bizon.yandex.api.IUserDataManager;
import ua.pp.bizon.yandex.api.ObjectLookup;
import ua.pp.bizon.yandex.uploader.atom.AppLink;
import ua.pp.bizon.yandex.uploader.utils.BrowserLaunch;

import java.io.UnsupportedEncodingException;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.entity.StringEntity;

/**
 * 
 * @author Bizon
 */
public class LoginCodeDialog extends javax.swing.JDialog implements ILogin {

	private static final long serialVersionUID = -496628456990549510L;

	/** Creates new form LoginCodeDialog */
	public LoginCodeDialog(java.awt.Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();
		urlTextField.setEditable(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        urlLabel = new javax.swing.JLabel();
        urlTextField = new javax.swing.JTextField();
        openButton = new javax.swing.JButton();
        codeLabel = new javax.swing.JLabel();
        codeTextField = new javax.swing.JTextField();
        okButton = new javax.swing.JButton();
        saveTokenCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        urlLabel.setText("Open url:");

        urlTextField.setText("https://oauth.yandex.ru/authorize?response_type=code&client_id=b765f9edc02c4171a95b7aee7bcf2ef7");

        openButton.setText("open");
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });

        codeLabel.setText("Input code:");

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        saveTokenCheckBox.setText("save token");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(urlLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(urlTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(codeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(codeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveTokenCheckBox)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(openButton)
                    .addComponent(okButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(urlLabel)
                    .addComponent(urlTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(openButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(codeLabel)
                        .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(okButton))
                    .addComponent(saveTokenCheckBox))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_openButtonActionPerformed
		BrowserLaunch.openURL(urlTextField.getText());
	}// GEN-LAST:event_openButtonActionPerformed

	private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okButtonActionPerformed
		if (codeTextField.getText().isEmpty()) {
			JOptionPane.showMessageDialog(null, "Please input code!");
		}
		String code = codeTextField.getText();
		try {
			String token = ObjectLookup
					.lookup(IHttpRemoteUtils.class)
					.post(new StringEntity("grant_type=authorization_code&client_id=b765f9edc02c4171a95b7aee7bcf2ef7&code=" + code),
							new AppLink(new String("https://oauth.yandex.ru/token")), "application/x-www-form-urlencoded", null).substring(18, 50);
			ObjectLookup.lookup(IUserDataManager.class).relogin(token);
			if (saveTokenCheckBox.isSelected()) {
				ObjectLookup.lookup(IUserDataManager.class).save();
			}
			setVisible(false);
		} catch (UnsupportedEncodingException e) {
			JOptionPane.showMessageDialog(null, "Error: " + e.getLocalizedMessage());
			LogFactory.getLog(getClass()).warn(e.getMessage(), e);
		} catch (HttpException e) {
			JOptionPane.showMessageDialog(null, "Error: " + e.getLocalizedMessage());
			LogFactory.getLog(getClass()).warn(e.getMessage(), e);
		}
	}// GEN-LAST:event_okButtonActionPerformed

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				LoginCodeDialog dialog = new LoginCodeDialog(new javax.swing.JFrame(), true);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {
					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel codeLabel;
    private javax.swing.JTextField codeTextField;
    private javax.swing.JButton okButton;
    private javax.swing.JButton openButton;
    private javax.swing.JCheckBox saveTokenCheckBox;
    private javax.swing.JLabel urlLabel;
    private javax.swing.JTextField urlTextField;
    // End of variables declaration//GEN-END:variables

	@Override
	public void setLogin(String string) {
		throw new RuntimeException("not implemented yet");
	}

	@Override
	public void waitUserData() {
		setVisible(true);
	}

	@Override
	public void unblockingWaitUserData() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				waitUserData();
			}
		});

	}
}
